<template lang="pug">
  .bill-table
    Modal(
      width="1100"
      v-model="isShowExportEmployeeModal"
      title="选择员工"
      class-name="vertical-center-modal"
    )
      //- .clearfix.mb-24
      //-   RadioGroup(v-model="differentSecurity" @on-change="securityChange")
      //-     Radio.display-block.mb-5(v-for="(item, index) of commercialArr" :label="item.securityGUID" :key="index") {{item.securityNO}}

      //- .clearfix.mb-24
      //-   Input(v-model="searchIdCardNo" search placeholder="请输入待选员工的身份证号进行搜索，用空格分开" :disabled="!currentSecurityNO" @on-search="getApplyUsers")

      .clearfix
        .ivu-transfer-list.w600.custom-transfer.pull-left
          Row.ivu-transfer-list-header
            Col(span="6") 已选员工
            Col(span="13")
              Button(size="small" @click="handlePrev" :disabled="!(transferData.length > 0 && tableComone.pageIndex > 1)") 上页
              span.pl-5.pr-5.font-12.text-gray-9 {{tableComone.pageIndex}}
              Button(size="small" @click="handleNext" :disabled="!(transferData.length > 0 && tableComone.pageIndex < tableComone.totalPages)") 下页
            Col.text-right(span="5") {{selectTransferData.length}}/{{transferData.length}}

          .ivu-transfer-list-body.pt-4.pb-4
            .clearfix.pall-10
              //- Input(v-model="employeeNameOrIdCardNo" search placeholder="请输入搜索内容" @on-search="getApplyUsers")
              Row
                Col(span="10")
                  Input.ivu-input-hasborder(v-model="name")
                    span(slot="prepend") 姓名：
                Col.pl-10(span="10")
                  Input.ivu-input-hasborder(v-model="idCardNos")
                    span(slot="prepend") 身份证：
                Col.pl-10(span="4")
                  Button(type="info" @click="getApplyUsers") 查询
            Checkbox(
              v-if="transferData.length"
              :indeterminate="indeterminateTransferData"
              :value="checkAllTransferData"
              @click.prevent.native="handleCheckAllTransferData"
            ) 全选
            CheckboxGroup(v-model="selectTransferData" @on-change="handleCheckboxChangeTransferData")
              Checkbox.display-block(v-for="(c_item, idx) of transferData" :key="idx" :label="c_item.id") {{c_item.name}} ({{c_item.idCardNo}})

        .w28.pull-left.ml-10.mr-10.pt-100
          Button.action-icon.mb-10(icon="ios-arrow-forward" :disabled="!(selectTransferData.length > 0)" @click="handleTransfer(selectTransferData, 'transferData', 'targetKeys')")
          Button.action-icon(icon="ios-arrow-back" :disabled="!(selectTargetKeys.length > 0)" @click="handleTransfer(selectTargetKeys, 'targetKeys', 'transferData')")

        .ivu-transfer-list.w420.custom-transfer.pull-left
          Row.ivu-transfer-list-header
            Col(span="18")
              span.pull-left.mr-10 暂缓发放员工
            Col.text-right(span="6") {{selectTargetKeys.length}}/{{targetKeys.length}}
          .ivu-transfer-list-body.pt-4.pb-4
            Checkbox(
              v-if="targetKeys.length"
              :indeterminate="indeterminateTargetKeys"
              :value="checkAllTargetKeys"
              @click.prevent.native="handleCheckAllTargetKeys"
            ) 全选
            CheckboxGroup(v-model="selectTargetKeys" @on-change="handleCheckboxChangeTargetKeys")
              Checkbox.display-block(v-for="(c_item, idx) of targetKeys" :key="idx" :label="c_item.id") {{c_item.name}} ({{c_item.idCardNo}})
      .clearfix.pt-20
        .w100.pull-left.line-h-32.mr-5 附件上传：
        Upload.pull-left.mb-5(
          ref="upload"
          :show-upload-list="false"
          accept=".doc, .docx, .xls, .xlsx, .pptx, .jpg, .jpeg, .png, .rar"
          :action="baseUrl + 'api/FinanceSSPayable/AnnexUpload?categoryName=商保生成付款单'"
          :on-success="uploadSuccess"
          :headers="headers"
          :max-size="10 * 1024"
          :on-exceeded-size="handleMaxSizeTen"
        )
          Button.download-btn(type="info") 点击上传
        div.pull-left.line-h-32.ml-10(v-if="fileObj && fileObj.Id")
          span.mr-10 {{fileObj.Name}}
          Icon.cursor-pointer.text-error(type="ios-close-circle" @click="removeFile")

      //- .clearfix(v-if="pageType !== 3")
      //-   p.text-center.text-error.mb-30.pt-50 温馨提示：不选择项目的时候为默认导出全部！
      //-   Form.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="110")
      //-     FormItem.form-item(v-for="(item, index) of formItem" :label="item.label" :key="index" :prop="item.prop")
      //-       template(v-if="item.type === 'select'")
      //-         Select(v-model="formData[item.model]" :placeholder="item.placeholder" label-in-value @on-change="projectChange" clearable)
      //-           Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}

      .search-form.pt-20(v-if="isWorkFlow")
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="setRules" :label-width="100")
          FormItem.form-item.ivu-col.pr-20(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" :type="item.model == 'amt' ? 'number' : 'text'" @on-blur="(event, type) => listenCall(item.fn, item.model, formData[item.model])")
              Input(v-else v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" :type="item.model == 'amt' ? 'number' : 'text'")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="c_item.value" :key="c_index" ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(v-for="(c_item, c_index) in arrListDown[item.options]" :value="item.model == 'payType' ? c_item.label : c_item.value" :key="c_index" ) {{ c_item.label }}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-model="formData[item.model]" placeholder="请选择" type="month" format="yyyy-MM")
            template(v-if="item.type === 'radio'")
              RadioGroup(v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item, c_index) in arrListDown[item.options]" :value="c_item.value" :key="c_index") {{ c_item.label }}

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="isWorkFlow" type="primary" :disabled="transferData.length == 0" @click="handleSubmit" :loading="!isCanSubmit") 确定
        Button(v-if="!isWorkFlow" type="primary" :disabled="transferData.length == 0" @click="handleSubmit2" :loading="!isCanSubmit") 确定
        //- Button(type="primary"  @click="handleShowChooseTypeModal") 临时弹窗
</template>

<script>
import { FinanceSPayableApi } from '@/api/FinanceSPayable.api.js'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import Cookies from 'js-cookie'

export default {
  name: '',

  props: {
  },

  components: {
  },

  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    setRules () {
      if (this.isWorkFlow) {
        if (this.formData.auditType == 1) {
          console.log('垫款金额字段 隐藏')
          this.rules.advanceAmt = []
        } else if (this.formData.auditType == 2) {
          console.log('垫款金额字段 显示')
          this.rules.advanceAmt = [{ required: true, message: '请输入垫款金额', trigger: 'change' }, { validator: this.validateAmt, trigger: 'blur' }]
        }
        return this.rules
      } else {
        return {}
      }
    }
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isList: null,
      parentRow: null,
      modalKey: null,
      isShowExportEmployeeModal: false,
      applyUsersList: [],
      transferData: [], // 待选员工列表
      selectTransferData: [],
      targetKeys: [], // 已选员工列表
      selectTargetKeys: [],
      selectArr: [],
      isCanSubmit: true,
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 100, // 当前页面展示条数
        totalPages: 0
      },
      formData: {
        auditType: null,
        advanceAmt: null,
        explain: null,
      },
      formItem: [
        { type: 'select', label: '审批方式：', placeholder: '请选择审批方式', prop: 'auditType', model: 'auditType', style: 'ivu-col-span-12', options: 'auditTypeOps', fn: 'auditTypeChange' },
        { type: 'input', label: '垫付金额：', placeholder: '请输入垫付金额', prop: 'advanceAmt', model: 'advanceAmt', style: 'ivu-col-span-12' },
        { type: 'input', label: '说明：', placeholder: '请输入说明', prop: 'explain', model: 'explain', style: 'ivu-col-span-12' },
      ],
      rules: {
        auditType: [
          { required: true, message: '请选择审批方式', trigger: 'change' }
        ],
        advanceAmt: [
          { required: true, message: '请输入垫付金额', trigger: 'change' }
        ],
      },
      arrListDown: {
        BillMergeProject: [],
        auditTypeOps: [{label: '常规请款审批', value: '1'}, {label: '垫付请款审批', value: '2'}]
      },
      indeterminateTransferData: false,
      checkAllTransferData: false,
      indeterminateTargetKeys: false,
      checkAllTargetKeys: false,
      // employeeNameOrIdCardNo: null,
      pageType: null,
      companyIds: null,
      selectedProject: null,
      beginTime: null,
      endTime: null,
      name: null, // 姓名搜索
      idCardNos: null, // 身份证搜索
      fileObj: null,
    }
  },

  watch: {
  },

  mounted () {
    this.getEnum()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典
    getEnum () {
      let typeName = 'BillMergeProject'
      Common.getSelectValueList(typeName, this.arrListDown)
    },

    ok () {
    },

    cancel () {
      this.isShowExportEmployeeModal = false
    },

    show (row) {
      if (this.isWorkFlow) {
        this.$refs.formData.resetFields()
      }
      this.parentRow = row
      this.isShowExportEmployeeModal = true
      this.isCanSubmit = true
      this.transferData = []
      this.targetKeys = []
      // this.employeeNameOrIdCardNo = ''
      this.name = null
      this.idCardNos = null
      this.fileObj = null
    },

    // 获取用户列表
    async getApplyUsers () {

      var removeEmployeeIds = this.targetKeys.map(item => { return item.id })
      var params = {
        ID: this.modalKey == 'fromList' ? this.parentRow.id : this.$route.query.salaryID,
        SalaryMonth: this.modalKey == 'fromList' ? this.parentRow.salaryMonth : this.$route.query.salaryMonth,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        Name: this.name,
        IdCardNos: this.idCardNos,
      }
      let res = await FinanceSPayableApi.getApplyUsers(params)
      console.log('获取用户列表: ', res)
      
      if (res.data.success) {
        this.tableComone.totalPages = res.data.totalPages
        this.tableComone.totalRows = res.data.totalRows
        let transferData = res.data.data.map(item => {return {id: item.employeeGUID, name: item.name, idCardNo: item.idCardNo}})
        this.applyUsersList = res.data.data
        for (var i = 0; i < transferData.length; i++) {
          for (var j = 0; j < removeEmployeeIds.length; j++) {
            if (transferData[i].id == removeEmployeeIds[j]) {
              transferData.splice(i, 1)
              i--
              if (i<0) {
                break
              }
            }
          }
        }
        this.transferData = transferData
      }
    },

    // 穿梭框操作
    handleTransfer (arr, currentArr, targetArr) {
      this.indeterminateTransferData = false,
      this.checkAllTransferData = false,
      this.indeterminateTargetKeys = false,
      this.checkAllTargetKeys = false
      
      var tempArr = []
      arr.map(c_item => {
        for (var i = 0; i < this[currentArr].length; i++) {
          if (c_item === this[currentArr][i].id) {
            tempArr.push(this[currentArr][i])
            this[currentArr].splice(i, 1) // 删除当前列表中相应的员工
          }
        }
      })
      this.selectTransferData = []
      this.selectTargetKeys = []
      this[targetArr] = this[targetArr].concat(tempArr) // 所选择的员工加入目标列表
      console.log('❤ targetKeys: ', this.targetKeys)

      this.name = null
      this.getApplyUsers()
    },

    searchFn (value) {
      console.log('value: ', value)
    },

    projectChange (value) {
      console.log('value: ', value)
      this.selectedProject = value
    },

    // 确定提交（有审批流）
    async handleSubmit () {
      var dataArr = this.targetKeys.map(item => {
        return {EmployeeGUID: item.id, Name: item.name}
      })
      var params = {
        IsList: this.isList,
        SalaryID: this.modalKey == 'fromList' ? this.parentRow.id : this.$route.query.salaryID,
        CompanyID: this.modalKey == 'fromList' ? this.parentRow.customerGUID : this.$route.query.companyID,
        SalaryMonth: this.modalKey == 'fromList' ? this.parentRow.salaryMonth : this.$route.query.salaryMonth,
        Datas: dataArr,
        WFContent: {
          AuditType: this.formData.auditType,
          AdvanceAmt: this.formData.advanceAmt,
          Explain: this.formData.explain,
        },
        annexId: this.fileObj && this.fileObj.Id || null
      }
      console.log('确定提交 params: ', params)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          FinanceSPayableApi.postApplyUsers(params).then(res => {
            if (res.status === 200 && res.data.success) {
              // window.open(baseUrl + res.data.data, '_blank')
              this.$Message.success(res.data.message)
              this.isShowExportEmployeeModal = false
              this.$emit('query')
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
              this.isCanSubmit = true
            }
          })
        }
      })
    },

    // 确定提交（无审批流）
    async handleSubmit2 () {
      var dataArr = this.targetKeys.map(item => {
        return {EmployeeGUID: item.id, Name: item.name}
      })
      var params = {
        IsList: this.isList,
        SalaryID: this.modalKey == 'fromList' ? this.parentRow.id : this.$route.query.salaryID,
        CompanyID: this.modalKey == 'fromList' ? this.parentRow.customerGUID : this.$route.query.companyID,
        SalaryMonth: this.modalKey == 'fromList' ? this.parentRow.salaryMonth : this.$route.query.salaryMonth,
        Datas: dataArr,
        WFContent: {
          AuditType: null,
          AdvanceAmt: null,
          Explain: null,
        },
        annexId: this.fileObj && this.fileObj.Id || null
      }
      console.log('确定提交 params: ', params)
      FinanceSPayableApi.postApplyUsers(params).then(res => {
        this.isCanSubmit = false
        if (res.status === 200 && res.data.success) {
          // window.open(baseUrl + res.data.data, '_blank')
          this.$Message.success(res.data.message)
          this.isShowExportEmployeeModal = false
          this.$emit('query')
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
          this.isCanSubmit = true
        }
      })
    },

    // 遍历待选员工列表
    handleMapTransferData (arr, idCardNoArr) {
      var tempArr = []
      arr.map((item, index) => {
        if (idCardNoArr.indexOf(item.idCardNo) === -1) {
          tempArr.push(item)
        }
      })
      return tempArr
    },

    handleCheckboxChangeTransferData (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.transferData.length) {
        this.indeterminateTransferData = false
        this.checkAllTransferData = true
      } else if (idArr.length > 0) {
        this.indeterminateTransferData = true
        this.checkAllTransferData = false
      } else {
        this.indeterminateTransferData = false
        this.checkAllTransferData = false
      }

      this.transferData.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTransferData = tempIdArr
    },

    handleCheckboxChangeTargetKeys (idArr) {
      console.log('🚩idArr: ', idArr)
      var tempIdArr = []
      if (idArr.length === this.targetKeys.length) {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = true
      } else if (idArr.length > 0) {
        this.indeterminateTargetKeys = true
        this.checkAllTargetKeys = false
      } else {
        this.indeterminateTargetKeys = false
        this.checkAllTargetKeys = false
      }

      this.targetKeys.map(item => {
        if (idArr.indexOf(item.id) !== -1) {
          tempIdArr.push(item.id) // code数组
        }
      })

      this.selectTargetKeys = tempIdArr
    },

    handlePrev () {
      this.tableComone.pageIndex--
      this.getApplyUsers()
    },

    handleNext () {
      this.tableComone.pageIndex++
      this.getApplyUsers()
    },

    // 待选员工全选
    handleCheckAllTransferData () {
      if (this.indeterminateTransferData) {
        this.checkAllTransferData = false;
      } else {
        this.checkAllTransferData = !this.checkAllTransferData;
      }
      this.indeterminateTransferData = false;

      var tempIdArr = []
      if (this.checkAllTransferData) {
        tempIdArr = this.transferData.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTransferData = tempIdArr
      console.log('❤ this.selectTransferData: ', this.selectTransferData)
    },

    // 已选员工全选
    handleCheckAllTargetKeys () {
      if (this.indeterminateTargetKeys) {
        this.checkAllTargetKeys = false;
      } else {
        this.checkAllTargetKeys = !this.checkAllTargetKeys;
      }
      this.indeterminateTargetKeys = false;

      var tempIdArr = []
      if (this.checkAllTargetKeys) {
        tempIdArr = this.targetKeys.map(item => {
          return item.id
        })
      } else {
        tempIdArr = [];
      }
      this.selectTargetKeys = tempIdArr
      console.log('❤ this.selectTargetKeys: ', this.selectTargetKeys)
    },

    handleShowChooseTypeModal () {
      this.$emit('handleShowChooseTypeModal') // 临时看效果
    },

    // 审批方式改变
    auditTypeChange (model, value) {
      console.log('审批方式改变 model: ', model, ', value: ', value)
      if (value == '1') {
        console.log('垫款金额字段 隐藏')
        this.formItem.map(item => {
          if (item.model == 'advanceAmt') {
            item.style = 'ivu-col-span-12 display-none'
          }
        })
      } else if (value == '2') {
        console.log('垫款金额字段 显示')
        this.formItem.map(item => {
          if (item.model == 'advanceAmt') {
            item.style = 'ivu-col-span-12 display-block'
          }
        })
      }
      this.formData.advanceAmt = null
    },

    // 上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.file = null
      } else {
        this.file = file
        console.log('file: ', this.file)
      }
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.Code === 200 && res.Success) {
        this.fileObj = res.Data
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 移除附件
    removeFile () {
      this.fileObj = null
    },

    // 超过10M提示
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  },
}
</script>

<style lang="less" scope>
.ivu-transfer-list-header{
  height: 42px;
}
.custom-transfer{
  padding-top: 42px;
  height: 250px;
  .ivu-transfer-list-body{
    overflow-y: scroll;
    .ivu-checkbox-wrapper{
      padding: 3px 16px;
      margin: 0;
      clear: both;
      line-height: 25px;
      .ivu-checkbox{
        margin-right: 5px;
      }
    }
  }
  .ivu-transfer-operation{
    .ivu-btn {
      width: 28px;
      height: 25px;
      line-height: 23px;
      text-align: center;
      font-size: 14px;
      padding: 0;
      span{
        display: block;
      }
    }
  }
  .ivu-transfer-list-content-item{
    padding-top: 3px;
    padding-bottom: 3px;
  }
}
.action-icon{
  width: 28px;
  height: 25px;
  line-height: 23px;
  color: #c5c8ce;
  background-color: #f7f7f7;
  border: solid 1px #dcdee2;
  text-align: center;
  font-size: 14px;
  border-radius: 3px;
  transition: all .3s;
  cursor: pointer;
  padding: 0;
  &:hover{
    color: #fff;
    background-color: #2d8cf0;
    border-color: #2d8cf0;
  }
}
</style>
